package com.itheima.bos.web.action.system;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.itheima.bos.domain.system.User;
import com.itheima.bos.service.system.IUserSerivce;
import com.itheima.bos.web.action.common.BaseAction;

public class UserAction extends BaseAction<User> {

	@Autowired
	private IUserSerivce UserSerivce;

	@Action(value = "user_login", results = {
			@Result(name = "success", location = "index.html", type = "redirect"),
			@Result(name = "login", location = "login.html", type = "redirect") })
	public String login() {

		// 创建subject对象
		Subject subject = SecurityUtils.getSubject();
		// 用户信息
		AuthenticationToken token = new UsernamePasswordToken(
				model.getUsername(), model.getPassword());

		try {
			// 登录成功
			subject.login(token);
			return SUCCESS;
		} catch (AuthenticationException e) {
			e.printStackTrace();
			// 登录失败
			return LOGIN;
		}
	}

	@Action(value = "user_logout", results = { @Result(name = "success", location = "login.html", type = "redirect") })
	public String logout() {

		// 退出登录
		Subject subject = SecurityUtils.getSubject();

		subject.logout();

		return SUCCESS;
	}

	@Action(value = "user_list", results = { @Result(name = "success", type = "json") })
	public String list() {

		List<User> users = UserSerivce.findAll();

		pushPageDataToValueStack(users);
		return SUCCESS;
	}

	private String[] roleIds;
	
	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}

	@Action(value = "user_save", results = { @Result(name = "success", type = "redirect", location = "pages/system/userlist.html") })
	public String save() {

		UserSerivce.save(model,roleIds);
		return SUCCESS;
	}
}
